﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Http;
using BaseBll;
using BaseWebApi.App_Start;
using BaseWebApi.Common;
using BaseWebApi.Models;
using Common;
using Models;

namespace BaseWebApi.Controllers
{
    /// <summary>
    /// 付款登记
    /// </summary>
    [ControllerGroup(groupName: "PurchasePayRegist", useage: "采购管理-付款登记")]
    public class PurchasePayRegistController : BaseController
    {
        private JWTPlayloadInfo playload;
        private readonly PurchasePayRegistBll _instance = PurchasePayRegistBll.Instance;

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="pageIndex">当前页</param>
        /// <param name="pageSize">页尺寸</param>
        /// <param name="number">登记编号</param>
        /// <param name="person">登记人员</param>
        /// <param name="deptId">部门id</param>
        /// <param name="invoiceNo">发票号</param>
        /// <param name="date">登记时间</param>
        /// <param name="supplierName">供应商</param>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage GetPageList(int pageIndex = 1, int pageSize = 10, string number = "", string person = "", int deptId = 0, string invoiceNo = "", string date = "", string supplierName = "")
        {
            StringBuilder strWhere = new StringBuilder("");
            if (!string.IsNullOrEmpty(number))
            {
                strWhere.Append(" and PPR_Number like '%" + number + "%'");
            }
            if (!string.IsNullOrEmpty(person))
            {
                strWhere.Append(" and PPR_Person like '%" + person + "%'");
            }
            if (deptId != 0)
            {
                strWhere.Append(" and PPR_DeptId = " + deptId);
            }
            if (!string.IsNullOrEmpty(invoiceNo))
            {
                strWhere.Append(" and PPR_InvoiceNo like '%" + invoiceNo + "%'");
            }
            if (!string.IsNullOrEmpty(date))
            {
                // 判断是否是日期格式
                if (DateTime.TryParse(date, out DateTime parsedDate))
                {
                    strWhere.Append(" and PPR_Date = '" + date + "'");
                }
                else
                {
                    return JsonHelper.ErrorJson("无效的日期格式");
                }
            }
            if (!string.IsNullOrEmpty(supplierName))
            {
                strWhere.Append(" and PO_SupplierName like '%" + supplierName + "%'");
            }

            DataTable dt = _instance.GetPageList(pageSize, pageIndex, strWhere.ToString(), "PPR_Date DESC", out int records);
            int totalPages = PageHelper.GetPageCount(pageSize, records);
            return JsonHelper.SuccessJson(CommonOperation.DataTable2JArray(dt), pageIndex, totalPages, records);
        }

        /// <summary>
        /// 查询付款申请（不分页）
        /// </summary>
        /// <param name="number"></param>
        /// <param name="person"></param>
        /// <param name="deptId"></param>
        /// <param name="invoiceNo"></param>
        /// <param name="date"></param>
        /// <param name="supplierName"></param>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage GetList(string number = "", string person = "", int deptId = 0, string invoiceNo = "", string date = "", string supplierName = "")
        {
            StringBuilder strWhere = new StringBuilder("");
            if (!string.IsNullOrEmpty(number))
            {
                strWhere.Append(" and PPR_Number like '%" + number + "%'");
            }
            if (!string.IsNullOrEmpty(person))
            {
                strWhere.Append(" and PPR_Person like '%" + person + "%'");
            }
            if (deptId != 0)
            {
                strWhere.Append(" and PPR_DeptId = " + deptId);
            }
            if (!string.IsNullOrEmpty(invoiceNo))
            {
                strWhere.Append(" and PPR_InvoiceNo like '%" + invoiceNo + "%'");
            }
            if (!string.IsNullOrEmpty(date))
            {
                // 判断是否是日期格式
                if (DateTime.TryParse(date, out DateTime parsedDate))
                {
                    strWhere.Append(" and PPR_Date = '" + date + "'");
                }
                else
                {
                    return JsonHelper.ErrorJson("无效的日期格式");
                }
            }
            if (!string.IsNullOrEmpty(supplierName))
            {
                strWhere.Append(" and PPR_SupplierName like '%" + supplierName + "%'");
            }

            List<PurchasePayRegistHead> list = _instance.GetList(strWhere.ToString());

            return JsonHelper.SuccessJson(JsonHelper.ListToJArray(list));
        }

        /// <summary>
        /// 根据ID获取实体对象
        /// </summary>
        /// <param name="ID">数据表ID</param>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage GetModel(int ID)
        {
            if (ID > 0)
            {
                PurchasePayRegistHead model = _instance.GetModelById(ID);
                if (model != null)
                {
                    // 查询文件
                    DataTable dt = UploadBll.Instance.GetFiles(ID, "PurchasePayRegist");
                    model.FileList = CommonOperation.ConvertDataTableToModelList<FileData>(dt);
                    return JsonHelper.SuccessJson(JsonHelper.ModelToJObject(model));
                }
                else
                {
                    return JsonHelper.FailJson("数据不存在");
                }
            }
            else
            {
                return JsonHelper.FailJson("参数错误");
            }
        }

        /// <summary>
        /// 新增付款登记
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage AddPurchasePayRegist([FromBody] PurchasePayRegistHead model)
        {
            playload = (JWTPlayloadInfo)Request.Properties["playload"];
            try
            {
                //验证各字段合法性
                string msg = "";
                bool isOk = _instance.VerifyModel(model, ref msg);
                if (isOk)
                {
                    var prbList = _instance.GetPRBList(model.ItemList);
                    bool res = _instance.AddPurchasePayRegist(model, prbList);
                    if (res)
                    {
                        // 更新文件信息
                        if (model.FileList != null && model.FileList.Count > 0)
                        {
                            UploadBll.Instance.Update(model.ID, model.FileList);
                        }

                        LogHelper.LogAction(playload, Constant.SysModule.PurchasePayRegist, Constant.ActionEnum.Add, "新增付款登记");
                        return JsonHelper.SuccessJson("新增成功");
                    }
                    else
                    {
                        LogHelper.LogWarn(playload, Constant.SysModule.PurchasePayRegist, Constant.ActionEnum.Add, "新增付款登记");
                        return JsonHelper.FailJson("新增失败");
                    }
                }
                else
                {
                    return JsonHelper.FailJson(msg);
                }
            }
            catch (Exception ex)
            {
                LogHelper.LogError(playload, ex, Constant.SysModule.PurchasePayRegist, Constant.ActionEnum.Add, "新增付款登记");
                throw;
            }
        }

        /// <summary>
        /// 删除付款登记
        /// </summary>
        /// <param name="id">ID</param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage DeletePurchasePayRegist(int id)
        {
            playload = (JWTPlayloadInfo)Request.Properties["playload"];
            try
            {
                if (id <= 0)
                {
                    return JsonHelper.FailJson("参数错误！");
                }
                else
                {
                    bool result;
                    // 先删除相关图片
                    DataTable dt = UploadBll.Instance.GetFiles(id, "PurchasePayRegist");
                    if (dt.Rows.Count > 0)
                    {
                        List<FileData> files = CommonOperation.ConvertDataTableToModelList<FileData>(dt);
                        string fid = "";
                        for (int i = 0; i < files.Count; i++)
                        {
                            if (string.IsNullOrEmpty(fid))
                            {
                                fid = "'" + files[i].RelationId + "'";
                            }
                            else
                            {
                                fid += ",'" + files[i].RelationId + "'";
                            }
                        }
                        bool res = UploadBll.Instance.DeleteFiles(fid, "PurchasePayRegist", files);
                        if (res)
                        {
                            LogHelper.LogAction(playload, Constant.SysModule.PurchasePayRegist, Constant.ActionEnum.Delete, "删除所有文件(HeadID:" + id + ")");
                            result = _instance.DeletePurchasePayRegist(id);
                            if (result)
                            {
                                LogHelper.LogAction(playload, Constant.SysModule.PurchasePayRegist, Constant.ActionEnum.Delete, "删除付款登记");
                                return JsonHelper.SuccessJson("删除成功");
                            }
                            else
                            {
                                LogHelper.LogWarn(playload, Constant.SysModule.PurchasePayRegist, Constant.ActionEnum.Delete, "删除付款登记");
                                return JsonHelper.SuccessJson("删除失败");
                            }
                        }
                        else
                        {
                            LogHelper.LogWarn(playload, Constant.SysModule.PurchasePayRegist, Constant.ActionEnum.Delete, "删除所有文件(HeadID:" + id + ")");
                            return JsonHelper.FailJson("删除文件失败");
                        }
                    }
                    else
                    {
                        result = _instance.DeletePurchasePayRegist(id);
                        if (result)
                        {
                            LogHelper.LogAction(playload, Constant.SysModule.PurchasePayRegist, Constant.ActionEnum.Delete, "删除付款登记");
                            return JsonHelper.SuccessJson("删除成功");
                        }
                        else
                        {
                            LogHelper.LogWarn(playload, Constant.SysModule.PurchasePayRegist, Constant.ActionEnum.Delete, "删除付款登记");
                            return JsonHelper.SuccessJson("删除失败");
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                LogHelper.LogError(playload, ex, Constant.SysModule.PurchasePayRegist, Constant.ActionEnum.Delete, "删除付款登记");
                throw;
            }
        }

        #region 上传文件相关

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns></returns>
        public HttpResponseMessage UploadFile()
        {
            JWTPlayloadInfo playload = (JWTPlayloadInfo)Request.Properties["playload"];

            List<FileData> list = new List<FileData>();
            HttpFileCollection files = HttpContext.Current.Request.Files;
            foreach (var key in files.AllKeys)
            {
                HttpPostedFile postedFile = files[key];
                if (!string.IsNullOrEmpty(postedFile.FileName))
                {
                    // file.SaveAs(HttpContext.Current.Server.MapPath("~/imgcoll/") + file.FileName);
                    //文件扩展名，不含“.”
                    string fileExt = Utils.GetFileExt(postedFile.FileName);

                    // 文件类型
                    Regex regex = new Regex(@"pdf|doc|docx|xlsx|xls");
                    bool isMatch = regex.IsMatch(fileExt);
                    if (!isMatch)
                    {
                        return JsonHelper.ErrorJson("文件类型不匹配");
                    }

                    FileData model = UploadHelper.SaveFilePic(postedFile, UploadHelper.uploadPath + "files/pc/purchase/payRegist/" + DateTime.Now.ToString("yyyyMMdd"), DateTime.Now.ToString("yyyyMMddHHmmss"));

                    // 文件类型
                    model.FileType = fileExt;

                    // 关联表
                    model.RelationTable = "PurchasePayRegist";

                    if (model != null)
                    {
                        list.Add(model);
                    }
                    else
                    {
                        continue;
                    }
                }
            }
            if (list.Count > 0)
            {
                bool result = UploadBll.Instance.AddList(list);
                if (result)
                {
                    LogHelper.LogAction(playload, Constant.SysModule.PurchasePayRegist, Constant.ActionEnum.Upload, "上传文件");
                    return JsonHelper.SuccessJson(JsonHelper.ListToJArray(list));
                }
                else
                {
                    LogHelper.LogWarn(playload, Constant.SysModule.PurchasePayRegist, Constant.ActionEnum.Upload, "上传文件");
                    return JsonHelper.ErrorJson("上传失败，稍后重试");
                }
            }
            else
            {
                return JsonHelper.ErrorJson("没有匹配的文件类型");
            }
        }

        /// <summary>
        /// 根据文件ID删除文件
        /// </summary>
        /// <param name="fileID">文件ID</param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage DeletePic(string fileID)
        {
            JWTPlayloadInfo playload = (JWTPlayloadInfo)Request.Properties["playload"];
            if (string.IsNullOrEmpty(fileID))
            {
                return JsonHelper.ErrorJson("参数错误");
            }
            FileData model = UploadBll.Instance.GetFileByID(fileID);
            if (model != null)
            {
                bool res = UploadBll.Instance.DeleteFilesByID(fileID, model);
                if (res)
                {
                    LogHelper.LogAction(playload, Constant.SysModule.PurchasePayRegist, Constant.ActionEnum.Delete, "删除文件(ID:" + fileID + ")");
                    return JsonHelper.SuccessJson("删除成功！");
                }
                else
                {
                    LogHelper.LogWarn(playload, Constant.SysModule.PurchasePayRegist, Constant.ActionEnum.Delete, "删除文件(ID:" + fileID + ")");
                    return JsonHelper.FailJson("删除失败！");
                }
            }
            else
            {
                return JsonHelper.FailJson("参数错误！,文件不存在");
            }
        }

        #endregion 上传文件相关

    }
}
